import { createApp } from "./main";
import { renderToString } from "vue/server-renderer";

export const render = async (url) => {
  const { app, router, pinia } = createApp();
  // set the router to the desired URL before rendering
  await router.push(url);
  await router.isReady();// 注入vue ssr中的上下文对象
  const renderCtx= {};
  const renderedHtml = await renderToString(app, renderCtx);
  
  const matchedComponents = router.currentRoute.value.matched.flatMap(record =>Object.values(record.components)
)
  // let matchedComponents = router.currentRoute.value.matched
  await Promise.all(
    matchedComponents.map((Component) => {
      // 如果组件中定义了asyncData函数，说明这个组件需要去后台获取接口数据
      if (Component.asyncData) {
        return Component.asyncData({
          // 传入store和当前route，store参数用来执行store.dispatch，发起请求
          pinia:pinia,
          route: router.currentRoute
        })
      }
      return []
    })
  )

  const state = JSON.stringify(pinia.state.value);

  return { renderedHtml,state };
}; 
